package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: 李旭
 * @Time: 11:17
 * @Description:
 *
 * 支付宝微服务
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayApiController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    //支付宝支付
    @ResponseBody
    @GetMapping("/submit/{orderId}")
    public String submit(@PathVariable Long orderId){

        return alipayService.submit(orderId);
    }
    //同步通知URl
    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }
    //异步通知
    @ResponseBody
    @PostMapping("/callback/notify")//Springmvc
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){
        //将异步通知中收到的所有参数都存放到map中
        System.out.println(paramsMap);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramsMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type); //调用SDK验证签名
            if(signVerified){
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                //二次校验  金额  交易号  交易状态
                System.out.println("验签成功");
                //简单写
                if(paramsMap.get("trade_status").equals("TRADE_SUCCESS")){
                    //交易成功
                    System.out.println("交易成功");
                    //更新支付表
                    paymentService.updateStatus(paramsMap);

                }else{
                    return "failure";
                }
                return "success";
            }else{
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }

    //退款
    @GetMapping("/refund/{outTradeNo}")
    @ResponseBody
    public Result refund(@PathVariable String outTradeNo){
        alipayService.refund(outTradeNo);
        return Result.ok();
    }

}
